﻿#include "ssLeServerThread.h"
#include "ssLeNetwork.h"

namespace StarSeeker
{

ssLeServerThread::ssLeServerThread()
{
	m_isClient = false;
	m_pNetwork = 0;
}

ssLeServerThread::~ssLeServerThread()
{
	StopNetWork();
}

bool ssLeServerThread::StartNetWork(const char* ip, const u16 port, bool isClient, ssLeNetwork* pNetwork)
{
	m_isClient = isClient;
	m_pNetwork = pNetwork;
	if (isClient)
	{
		if (CreateConnect(ip, port))
		{
			return StartThread();
		}
	}
	else if(CreateListen(ip, port))
	{
		return StartThread();
	}
	return false;
}

void ssLeServerThread::StopNetWork()
{
	StopServer();
	RequestStop();
	WaitForExit();
}

bool ssLeServerThread::Reconnect()
{
	if (m_isClient)
	{
		StopNetWork();
		if (CreateConnect(m_connectIP.c_str(), m_connectPort))
		{
			return StartThread();
		}
	}
	return false;
}

void ssLeServerThread::SetRWSize(u32 len)
{
	SetRWBufferSize(len);
}

void ssLeServerThread::SetParsePackageMode(u8 mode)
{
	m_parsePackageMode = mode;
}

void ssLeServerThread::ThreadMemberFunc()
{
	StartDispatch();
}

void ssLeServerThread::OnNewConnection(ssLeSession *session)
{
	if (m_pNetwork)
	{
		m_pNetwork->PostMsg(SS_MSG_NEW_CONNECT, 0, 0, (ulint)session, 0);
	}
}

void ssLeServerThread::OnReceive(ssLeSession *session, char *data, u32 len)
{
	if (m_pNetwork)
	{
		m_pNetwork->PostMsg(SS_MSG_NEW_CONNECT, 0, 0, (ulint)session, 0);
	}
	else
	{
		ssLeServer::OnReceive(session, data, len);
	}
}

void ssLeServerThread::OnError(ssLeSession *session, short error)
{
	if (m_pNetwork)
	{
		m_pNetwork->PostMsg(SS_MSG_DISCONNECT, error, session->m_sessionID, (ulint)session, 0);
	}
	else
	{
		ssLeServer::OnError(session, error);
	}
}

}
